const mongoose = require('mongoose')
const {
  resolve
} = require('path')
const glob = require('glob')
mongoose.Promise = global.Promise;

exports.initSchema = () => {
  glob.sync(resolve(__dirname, './schema', '**/*.js')).forEach(require)
}

exports.connect = (db) => {
  let maxConnectTimes = 0
  return new Promise(resolve => {
    if (process.env.NODE_ENV !== 'production') {
      mongoose.set('debug', true)
    }
    /** * 连接 */
    mongoose.connect(db, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }, err => {
      if (err) console.log(err)
      else console.log('连接数据库成功')
    });
    /** * 连接成功 */
    mongoose.connection.on('connected', function () {
      resolve()
      console.log('Mongoose connection open to ' + db);
    });
    /** * 连接异常 */
    mongoose.connection.on('error', function (err) {
      maxConnectTimes++;
      if (maxConnectTimes < 5) {
        mongoose.connect(db)
      } else {
        throw new Error('数据库挂了吧少年')
      }
      console.log('Mongoose connection error: ' + err);
    });

    /** * 连接断开 */
    mongoose.connection.on('disconnect', function () {
      maxConnectTimes++;
      if (maxConnectTimes < 5) {
        mongoose.connect(db)
      } else {
        throw new Error('数据库挂了吧少年')
      }
      console.log('Mongoose connection disconnected');
    });

  })

}

// module.exports = mongoose;
